import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Form, Input, Button, DatePicker, Select, Space, Tag, Modal, message, Descriptions, Popconfirm } from 'antd';
import { SearchOutlined, ReloadOutlined, EyeOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';

const { RangePicker } = DatePicker;
const { Option } = Select;

// 获取团购订单列表
const fetchOrders = async (params) => {
  return request('/api/v1/groupbuy/order', {
    method: 'GET',
    params,
  });
};

// 获取团购订单详情
const fetchOrderDetail = async (id) => {
  return request(`/api/v1/groupbuy/order/${id}`, {
    method: 'GET',
  });
};

// 审核团购订单
const auditOrder = async (data) => {
  return request('/api/v1/groupbuy/order/audit', {
    method: 'POST',
    data,
  });
};

// 取消团购订单
const cancelOrder = async (data) => {
  return request('/api/v1/groupbuy/order/cancel', {
    method: 'POST',
    data,
  });
};

// 订单状态映射
const orderStatusMap = {
  1: { text: '待审核', color: 'gold' },
  2: { text: '已审核', color: 'blue' },
  3: { text: '已支付', color: 'cyan' },
  4: { text: '已完成', color: 'green' },
  5: { text: '已拒绝', color: 'red' },
  6: { text: '已取消', color: 'red' },
};

// 团购状态映射
const groupStatusMap = {
  1: { text: '待成团', color: 'gold' },
  2: { text: '已成团', color: 'green' },
  3: { text: '未成团', color: 'red' },
};

const GroupbuyOrder = () => {
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [auditForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  const [searchParams, setSearchParams] = useState({});
  const [detailVisible, setDetailVisible] = useState(false);
  const [auditVisible, setAuditVisible] = useState(false);
  const [currentOrder, setCurrentOrder] = useState(null);
  const [auditType, setAuditType] = useState('approve'); // approve or reject

  // 获取团购订单列表
  const fetchOrderList = async () => {
    try {
      setLoading(true);
      const res = await fetchOrders({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      });
      if (res.success) {
        setOrders(res.data.list || []);
      } else {
        message.error(res.message || '获取团购订单列表失败');
      }
    } catch (error) {
      console.error('获取团购订单列表出错:', error);
      message.error('获取团购订单列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchOrderList();
  }, [pagination.current, pagination.pageSize, searchParams]);

  // 查看订单详情
  const handleViewDetail = async (record) => {
    try {
      setLoading(true);
      const res = await fetchOrderDetail(record.id);
      if (res.success) {
        setCurrentOrder(res.data);
        setDetailVisible(true);
      } else {
        message.error(res.message || '获取订单详情失败');
      }
    } catch (error) {
      console.error('获取订单详情出错:', error);
      message.error('获取订单详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理审核
  const handleAudit = (record, type) => {
    setCurrentOrder(record);
    setAuditType(type);
    auditForm.resetFields();
    setAuditVisible(true);
  };

  // 提交审核
  const handleAuditSubmit = async () => {
    try {
      const values = await auditForm.validateFields();
      setLoading(true);
      
      const data = {
        id: currentOrder.id,
        status: auditType === 'approve' ? 2 : 5, // 2:已审核, 5:已拒绝
        remark: values.remark,
      };
      
      const res = await auditOrder(data);
      if (res.success) {
        message.success(`${auditType === 'approve' ? '审核通过' : '拒绝'}成功`);
        setAuditVisible(false);
        fetchOrderList();
      } else {
        message.error(res.message || `${auditType === 'approve' ? '审核通过' : '拒绝'}失败`);
      }
    } catch (error) {
      console.error('审核出错:', error);
      message.error('审核失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理取消订单
  const handleCancel = async (record) => {
    try {
      setLoading(true);
      const res = await cancelOrder({
        id: record.id,
        status: 6, // 6:已取消
      });
      if (res.success) {
        message.success('取消订单成功');
        fetchOrderList();
      } else {
        message.error(res.message || '取消订单失败');
      }
    } catch (error) {
      console.error('取消订单出错:', error);
      message.error('取消订单失败');
    } finally {
      setLoading(false);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '订单号',
      dataIndex: 'order_no',
      key: 'order_no',
      width: 180,
    },
    {
      title: '活动名称',
      dataIndex: 'activity_name',
      key: 'activity_name',
      width: 180,
    },
    {
      title: '用户',
      dataIndex: 'username',
      key: 'username',
      width: 120,
    },
    {
      title: '购买数量',
      dataIndex: 'quantity',
      key: 'quantity',
      width: 100,
    },
    {
      title: '订单金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      render: (amount) => `¥${(amount / 100).toFixed(2)}`,
    },
    {
      title: '团购状态',
      dataIndex: 'group_status',
      key: 'group_status',
      width: 100,
      render: (status) => {
        const { text, color } = groupStatusMap[status] || { text: '未知', color: 'default' };
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        const { text, color } = orderStatusMap[status] || { text: '未知', color: 'default' };
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '下单时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (time) => moment(time * 1000).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => {
        const actions = [
          <Button 
            key="view"
            type="link" 
            icon={<EyeOutlined />} 
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
        ];
        
        // 只有待审核状态才显示审核按钮
        if (record.status === 1) {
          actions.push(
            <Popconfirm
              key="approve"
              title="确定要通过此订单吗？"
              onConfirm={() => handleAudit(record, 'approve')}
              okText="确定"
              cancelText="取消"
            >
              <Button 
                type="link" 
                icon={<CheckOutlined />} 
                style={{ color: '#52c41a' }}
              >
                通过
              </Button>
            </Popconfirm>,
            <Popconfirm
              key="reject"
              title="确定要拒绝此订单吗？"
              onConfirm={() => handleAudit(record, 'reject')}
              okText="确定"
              cancelText="取消"
            >
              <Button 
                type="link" 
                icon={<CloseOutlined />} 
                danger
              >
                拒绝
              </Button>
            </Popconfirm>
          );
        }
        
        // 已审核但未支付的订单可以取消
        if (record.status === 2) {
          actions.push(
            <Popconfirm
              key="cancel"
              title="确定要取消此订单吗？"
              onConfirm={() => handleCancel(record)}
              okText="确定"
              cancelText="取消"
            >
              <Button 
                type="link" 
                danger
              >
                取消
              </Button>
            </Popconfirm>
          );
        }
        
        return <Space>{actions}</Space>;
      },
    },
  ];

  // 处理搜索
  const handleSearch = (values) => {
    const params = {};
    if (values.order_no) {
      params.order_no = values.order_no;
    }
    if (values.activity_name) {
      params.activity_name = values.activity_name;
    }
    if (values.username) {
      params.username = values.username;
    }
    if (values.status) {
      params.status = values.status;
    }
    if (values.group_status) {
      params.group_status = values.group_status;
    }
    if (values.date_range && values.date_range.length === 2) {
      params.startTime = values.date_range[0].format('YYYY-MM-DD HH:mm:ss');
      params.endTime = values.date_range[1].format('YYYY-MM-DD HH:mm:ss');
    }
    
    setSearchParams(params);
    setPagination({
      ...pagination,
      current: 1, // 重置到第一页
    });
  };

  // 重置搜索
  const handleReset = () => {
    form.resetFields();
    setSearchParams({});
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 处理表格变化
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination(pagination);
  };

  return (
    <PageContainer>
      <Card>
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 24 }}
        >
          <Form.Item name="order_no" label="订单号">
            <Input placeholder="请输入订单号" allowClear />
          </Form.Item>
          <Form.Item name="activity_name" label="活动名称">
            <Input placeholder="请输入活动名称" allowClear />
          </Form.Item>
          <Form.Item name="username" label="用户名">
            <Input placeholder="请输入用户名" allowClear />
          </Form.Item>
          <Form.Item name="status" label="订单状态">
            <Select placeholder="请选择订单状态" style={{ width: 150 }} allowClear>
              <Option value={1}>待审核</Option>
              <Option value={2}>已审核</Option>
              <Option value={3}>已支付</Option>
              <Option value={4}>已完成</Option>
              <Option value={5}>已拒绝</Option>
              <Option value={6}>已取消</Option>
            </Select>
          </Form.Item>
          <Form.Item name="group_status" label="团购状态">
            <Select placeholder="请选择团购状态" style={{ width: 150 }} allowClear>
              <Option value={1}>待成团</Option>
              <Option value={2}>已成团</Option>
              <Option value={3}>未成团</Option>
            </Select>
          </Form.Item>
          <Form.Item name="date_range" label="下单时间">
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              placeholder={['开始时间', '结束时间']}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <Table
          columns={columns}
          dataSource={orders}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 1300 }}
        />

        {/* 订单详情弹窗 */}
        <Modal
          title="团购订单详情"
          visible={detailVisible}
          onCancel={() => setDetailVisible(false)}
          footer={[
            <Button key="close" onClick={() => setDetailVisible(false)}>
              关闭
            </Button>,
          ]}
          width={800}
        >
          {currentOrder && (
            <Descriptions bordered column={2}>
              <Descriptions.Item label="订单号">{currentOrder.order_no}</Descriptions.Item>
              <Descriptions.Item label="活动名称">{currentOrder.activity_name}</Descriptions.Item>
              <Descriptions.Item label="用户名">{currentOrder.username}</Descriptions.Item>
              <Descriptions.Item label="联系电话">{currentOrder.phone}</Descriptions.Item>
              <Descriptions.Item label="购买数量">{currentOrder.quantity}</Descriptions.Item>
              <Descriptions.Item label="订单金额">¥{(currentOrder.amount / 100).toFixed(2)}</Descriptions.Item>
              <Descriptions.Item label="团购状态">
                <Tag color={
                  currentOrder.group_status === 1 ? 'gold' :
                  currentOrder.group_status === 2 ? 'green' :
                  currentOrder.group_status === 3 ? 'red' : 'default'
                }>
                  {{
                    '1': '待成团',
                    '2': '已成团',
                    '3': '未成团',
                  }[currentOrder.group_status] || currentOrder.group_status}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="订单状态">
                <Tag color={
                  currentOrder.status === 1 ? 'gold' :
                  currentOrder.status === 2 ? 'blue' :
                  currentOrder.status === 3 ? 'cyan' :
                  currentOrder.status === 4 ? 'green' :
                  currentOrder.status === 5 || currentOrder.status === 6 ? 'red' : 'default'
                }>
                  {{
                    '1': '待审核',
                    '2': '已审核',
                    '3': '已支付',
                    '4': '已完成',
                    '5': '已拒绝',
                    '6': '已取消',
                  }[currentOrder.status] || currentOrder.status}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="下单时间">
                {moment(currentOrder.created_at * 1000).format('YYYY-MM-DD HH:mm:ss')}
              </Descriptions.Item>
              <Descriptions.Item label="支付时间">
                {currentOrder.paid_at ? moment(currentOrder.paid_at * 1000).format('YYYY-MM-DD HH:mm:ss') : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="收货地址" span={2}>{currentOrder.address || '-'}</Descriptions.Item>
              <Descriptions.Item label="备注" span={2}>{currentOrder.remark || '-'}</Descriptions.Item>
            </Descriptions>
          )}
        </Modal>

        {/* 审核弹窗 */}
        <Modal
          title={`${auditType === 'approve' ? '审核通过' : '拒绝'}团购订单`}
          visible={auditVisible}
          onCancel={() => setAuditVisible(false)}
          footer={[
            <Button key="back" onClick={() => setAuditVisible(false)}>
              取消
            </Button>,
            <Button key="submit" type="primary" onClick={handleAuditSubmit}>
              确定
            </Button>,
          ]}
          width={500}
          destroyOnClose
        >
          <Form
            form={auditForm}
            layout="vertical"
          >
            <Form.Item
              name="remark"
              label="备注"
              rules={[{ required: true, message: '请输入备注' }]}
            >
              <Input.TextArea rows={4} placeholder="请输入备注" />
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </PageContainer>
  );
};

export default GroupbuyOrder;